const Article = require('../../models/blog_article');
const Category = require('../../models/blog_category');
const Tag = require('../../models/blog_tags');
const ArticleCategory = require('../../models/article_category_tags');
const Comment = require('../../models/blog_comment');

const User = require('../../models/blog_user'); // 前台用户表
const AdminUser = require('../../models/admin_users'); // 后台用户表
const Role = require('../../models/admin_role'); // 后台角色
const UserOrRole = require('../../models/admin_user_or_role'); // 后台用户角色关联表

const Utils = require('../../utils'); // 工具函数
const authCodeFunc = require('../../utils/authCode');

const knex = require('../../models/knex');

const ControllerArticle = {
    // 获取列表
    getList: async function (req, res, next) {
        try {
            let { support, per_page, page, category_id, tag_id } = req.query;
            let offset = (per_page * (page - 1)) || 0; //计算当前页
            let articles = Article.table;
            let categorys = Category.table;
            let or = ArticleCategory.table;
            let params = { status: 1 };
            let ids = []
            let list;

            // 文章关联信息表
            const ass = await knex(or)
                .join(categorys, `${or}.category_id`, `${categorys}.id`)
                .select(`${or}.article_id`, `${or}.category_id`, `${or}.tag_ids`, `${categorys}.title`,);

            const tags = await Tag.all();// 标签表

            // 把标签表信息储存到文章关联信息表中
            ass.forEach((v) => {
                v.tags = [];
                let tagIds = v.tag_ids.split(',');
                let ask = tagIds.some(v => v == tag_id);

                // 提取出关联表中的文章id，下面代码查询中用到
                if (ask) {
                    ids.push(v.article_id)
                }

                // 遍历关联信息表中的标签id
                tagIds.forEach((i) => {
                    // 遍历标签表
                    tags.forEach((t) => {
                        if (i == t.id) v.tags.push(t.title) // 比较两表信息，把标签信息储存到关联表
                    })
                })
            })

            if (Number(category_id)) params.category_id = category_id;
            if (Number(support)) params.support = support;

            if (!Number(tag_id)) { // 点击分类展示相应文章
                list = await knex(articles)
                    .join(or, `${articles}.id`, `${or}.article_id`)
                    .where(params)
                    .limit(Number(per_page)).offset(Number(offset))
                    .select(
                        `${articles}.id`, `${articles}.title`, `${articles}.summary`, `${articles}.status`,
                        `${articles}.support`, `${articles}.click`, `${articles}.image_url`, `${articles}.content`,
                        `${articles}.sort`, `${articles}.created_time`,
                    );
            } else { // 点击标签展示相应文章
                list = await knex(articles)
                    .where(params)
                    .whereIn('id', ids)
                    .limit(Number(per_page)).offset(Number(offset))
                    .select(
                        `${articles}.id`, `${articles}.title`, `${articles}.summary`, `${articles}.status`,
                        `${articles}.support`, `${articles}.click`, `${articles}.image_url`, `${articles}.content`,
                        `${articles}.sort`, `${articles}.created_time`,
                    );
            }

            // 把关联信息表的数据储存到文章表
            list.forEach((v) => {
                ass.forEach((i) => {
                    if (v.id == i.article_id) {
                        v.category_id = i.category_id;
                        v.tag_ids = i.tag_ids;
                        v.tags = i.tags;
                        v.category_title = i.title;
                    }
                })
            })

            const total = (await Article.select(params)).length; // 数据总数

            res.json({ code: 200, msg: '链接成功', data: { list, total } })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },

    // 获取详情
    getById: async function (req, res, next) {
        try {
            let { id } = req.query;

            const articles = await Article.select({ id });
            const assoc_lists = await ArticleCategory.select({ article_id: id });
            let tag_ids = assoc_lists[0].tag_ids.split(',').map(Number);
            const tags = await Tag.batchSelect(tag_ids);

            let list = {
                ...articles[0],
                tags
            }

            res.json({ code: 200, msg: '链接成功', data: { list } })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },

    // 纪录点击
    clickRecord: async function (req, res, next) {
        try {
            let { id } = req.query;

            const articles = await Article.select({ id });

            await Article.update(id, { click: articles[0].click + 1 })

            res.json({ code: 200, msg: '链接成功' })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },

    commentList: async function (req, res, next) {
        try {
            let { id, per_page, page } = req.query;
            let users = User.table;
            let adUser = AdminUser.table;
            let roles = Role.table;
            let comments = Comment.table;

            let admin = await knex(comments)
                .join(adUser, `${comments}.user_id`, `${adUser}.id`)
                .join(roles, `${comments}.role`, `${roles}.id`)
                .select(
                    `${comments}.id`,
                    `${comments}.comment_level`,
                    `${comments}.parent_comment_id`,
                    `${comments}.reply_comment_id`,
                    `${comments}.content`,
                    `${comments}.role`,
                    `${comments}.host`,
                    `${comments}.user_id`,
                    `${comments}.created_time`,
                    `${adUser}.user_name`,
                    `${adUser}.user_account as account`,
                    `${adUser}.user_avatar_url as avatar`,
                    `${roles}.name as role_name`,
                )
                .whereRaw(`${comments}.article_id = ${id}`)

            let web = await knex(comments)
                .join(users, `${comments}.user_id`, `${users}.id`)
                .select(
                    `${comments}.id`,
                    `${comments}.comment_level`,
                    `${comments}.parent_comment_id`,
                    `${comments}.reply_comment_id`,
                    `${comments}.content`,
                    `${comments}.role`,
                    `${comments}.host`,
                    `${comments}.user_id`,
                    `${comments}.created_time`,
                    `${users}.name as user_name`,
                    `${users}.account`,
                    `${users}.avatar_url as avatar`,
                )
                .whereRaw(`${comments}.article_id = ${id}`)

            // admin与web合并
            const newComment = admin.concat(web);

            // 按id升序排序
            newComment.sort((a, b) => {
                return a.id - b.id
            });

            const getComment = Utils.getData(newComment); // 树形数据处理索引0为一级，其他均为子级
            const commentData = Utils.getChildrenTree(getComment, getComment[0]); // 按父子关系处理分类
            const list = Utils.getPagination(commentData, per_page, page);

            let total = commentData.length; // 文章总数
            let number = Math.ceil(total / per_page); // 计算出信息总页数

            res.json({ code: 200, msg: '连接成功', data: { list, total, number } })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },

    /* 评论 */
    comment: async function (req, res, next) {
        try {
            let { content, comment_level, article_id } = req.body;
            let authorization = req.headers.authorization;
            let user_id = '';

            if (authorization) {
                let token = authorization.split(' ');
                let user_decode = authCodeFunc(token[1], 'DECODE');
                let user_info = user_decode.str.split('\t');
                user_id = user_info[0];
            } else {
                return res.json({ code: 0, msg: '还未登录' })
            }

            let params = {
                user_id,
                content: encodeURI(content),
                comment_level,
                article_id,
                created_time: new Date().getTime()
            }

            await Comment.insert(params);

            res.json({ code: 200, msg: '评论成功', data: {} })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },

    /* 回复 */
    reply: async function (req, res, next) {
        try {
            let { id, article_id, content, comment_level } = req.body;
            let authorization = req.headers.authorization;
            let user_id = '';

            if (authorization) {
                let token = authorization.split(' ');
                let user_decode = authCodeFunc(token[1], 'DECODE');
                let user_info = user_decode.str.split('\t');
                user_id = user_info[0];
            } else {
                return res.json({ code: 0, msg: '还未登录' })
            }

            const comments = await Comment.select({ id });
            let parent_comment_id = comments[0].parent_comment_id; // 父留言id
            let reply_comment_id = id;

            let params = {
                user_id,
                article_id,
                content: encodeURI(content),
                comment_level,
                parent_comment_id: parent_comment_id ? parent_comment_id : id,
                reply_comment_id,
                created_time: new Date().getTime()
            }

            console.log(params);

            await Comment.insert(params);

            res.json({ code: 200, msg: '评论成功', data: {} })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },
}

module.exports = ControllerArticle;
